package com.handtransaction.controller;

import com.handtransaction.entity.Category;
import com.handtransaction.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 处理类别的控制器
 */
@Controller
public class CategoryController {
    @Autowired
    private CategoryService categoryService;



    //查询所有类别
    @RequestMapping("/queryAllCategory")
    public String queryAllCategory(Model model, HttpServletRequest request){
        List<Category> list = categoryService.queryAllCategory();
        model.addAttribute("categories",list);
        request.getServletContext().setAttribute("categories",list);
        return "category/showAllCategory";
    }

    //新增类别
    @RequestMapping("/addCategory")
    public String addCategory(String cname){
        //int cid = categoryService.queryAllCategory().size();
        categoryService.addCategory(cname);
        return "redirect:/queryAllCategory";
    }

    //删除类别
    @RequestMapping("/deleteCategory")
    public String deleteCategory(int cid){
        categoryService.deleteCategory(cid);
        return "redirect:/queryAllCategory";
    }

    //点击【修改类别】，跳转到【类别修改页面】并展示数据
    @RequestMapping("/gotoUpdCatePage")
    public String gotoUpdateCategory(int cid, Model model){
        Category category = categoryService.queryCategoryById(cid);
        model.addAttribute("category" ,category);
        List<Category> list = categoryService.queryAllCategory();
        model.addAttribute("categories",list);
        return "category/showAllCategory";
    }

    //修改类别
    @RequestMapping("/updateCategory")
    public String updateCategory(Category category){
        categoryService.updateCategory(category);
        return "redirect:/queryAllCategory";
    }

    //查询类别 -- 通过类别名称的模糊查询
    @RequestMapping("/queryCategory")
    public String queryCategory(String cname, Model model){
        Category category = categoryService.queryCategory(cname);
        List<Category> list = new ArrayList<>();
        list.add(category);
        model.addAttribute("categories",list);
        System.out.println("【测试】"+category);
        //展示所有类别信息的jsp文件名为showAllCategory
        return "category/showAllCategory";
    }




}
